package com.yizhubao.app.activitys;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.yizhubao.app.R;
import com.yizhubao.app.base.BaseActivityToolBar;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import h.framework.pacy.utils.LogUtil;

/**
 * 创建人: PACY
 * 创建时间: 6/6/21 10:25 AM
 * 邮箱: pengwwe457621023@qq.com
 * 类描述: web activity
 */
public class WebActivity extends BaseActivityToolBar {
    String url;
    String title;

    @BindView(R.id.progress)
    ProgressBar progress;
    @BindView(R.id.web)
    WebView tenX5_webView;
    private WebSettings webSettings;

    private Map<String, String> header;

    @Override
    protected int setContentLayout() {
        return R.layout.activity_web;
    }

    @Override
    protected void initView() {
        Bundle bundle=getIntent().getExtras();
        url=bundle.getString("url");
        LogUtil.i(url);
        title=bundle.getString("title");
        if(title==null){
            title="";
        }
        setTitleOnLeftIcon(R.drawable.icon_back,"");
    }

    @Override
    protected void initData() {
        webSettings = tenX5_webView.getSettings();
        initWebView();//初始化腾讯 X5 webView
        loadWe();//腾讯 X5 加载网页

        if(tenX5_webView != null){
            if(url.contains("wxPay")){
                header=new HashMap<>();
                header.put("Referer","https://resource.weimingfang.com");
                tenX5_webView.loadUrl(url,header);//加载网页
            }else{
                tenX5_webView.loadUrl(url);//加载网页
            }

        }
    }

    /**
     * 激活 js 调用，设置 webView 活跃状态
     */
    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onResume() {
        super.onResume();

    }





    /**
     * 初始化腾讯 X5 webView
     */
    private void initWebView() {

        //视频为了避免闪屏和透明问题
//        getWindow().setFormat(PixelFormat.TRANSLUCENT);
//        //避免输入法界面弹出后遮挡输入光标的问题
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

    }


    /**
     * 腾讯 X5 加载网页
     */
    private void loadWe(){

        if(webSettings != null){
            webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
            webSettings.setJavaScriptEnabled(true);
            webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
            webSettings.setDisplayZoomControls(true); //隐藏原生的缩放控件
            webSettings.setBlockNetworkImage(false);//解决图片不显示
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);//设置允许js弹出alert对话框
            webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
            webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
            webSettings.setDomStorageEnabled(true);
            webSettings.setUseWideViewPort(true);
            webSettings.setLoadWithOverviewMode(true);
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        }

        if(tenX5_webView != null){

            //该界面打开更多链接
            tenX5_webView.setWebViewClient(new WebViewClient() {

                @Override
                public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                    LogUtil.i(s);
                    try {
                        if (s.startsWith("weixin://") || s.startsWith("alipays://")) {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            intent.setData(Uri.parse(s));
                            startActivity(intent);
                            return true;
                        }
                    } catch (Exception e) {
                        return false;
                    }
                    String referer = "https://resource.weimingfang.com";
                    if (s.contains("https://wx.tenpay.com")) {
                        Map<String, String> extraHeaders = new HashMap<>();
                        extraHeaders.put("Referer", referer);
                        webView.loadUrl(s, extraHeaders);
                        return true;
                    }

                    if(s.startsWith("closewebview://")){
                        runOnUiThread(() -> closeWebview());
                        return true;
                    }

                    webView.loadUrl(s);
                    return true;
                }

                @Override
                public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                    sslErrorHandler.proceed();
                    super.onReceivedSslError(webView, sslErrorHandler, sslError);
                }
            });

            //监听网页的加载进度
            tenX5_webView.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView webView, int i) {
                    //当前网页加载到 100% 后就显示 腾讯X5 的webView组件
                    if (i < 100) {
                        progress.setVisibility(View.VISIBLE);
                        progress.setProgress(i);
                    } else {
                        progress.setVisibility(View.GONE);
                        progress.setProgress(100);
                    }

                }
            });

        }

    }

    /**
     * 关闭webview
     */
    private void closeWebview(){
        setResult(1);
        finish();
    }


    /**
     * 退出界面暂停 webView的活跃
     */
    @Override
    protected void onPause() {
        super.onPause();
        tenX5_webView.onPause();
        tenX5_webView.getSettings().setLightTouchEnabled(false);
    }


    /**
     * 销毁 放置内存泄漏
     */
    @Override
    protected void onDestroy() {
        if (this.tenX5_webView != null) {
            tenX5_webView.destroy();
        }
        super.onDestroy();
    }
}